<template>
	<el-select
		v-model="value"
		placeholder="请输入关键词搜索"
		:multiple="multiple"
		@change="change"
		clearable
		filterable
		remote
		reserve-keyword
		:remote-method="getList"
		:loading="loading"
	>
		<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
	</el-select>
</template>
<script setup lang="ts" name="DxSelect">
import { onMounted, onUnmounted, ref, watch, inject } from 'vue';
import { axios } from '@/uni_modules/dx-admin/api/index';
import useElFormItem from '@/uni_modules/dx-admin/libs/useElFormItem';
const { emitTrigger } = useElFormItem();
const props = withDefaults(
	defineProps<{
		modelValue: any;
		multiple?: boolean;
		url: string;
		funcName?: string;
		labelField?: string;
		valueField?: string;
		searchField?: string;
		params?: any;
		more?: boolean;
		type?: string;
	}>(),
	{
		multiple: false,
		funcName: 'dx-func-admin',
		labelField: 'name',
		valueField: '_id',
		params: {},
		more: true,
		type: 'edit',
	}
);
const loading = ref(false);
const value = ref(props.multiple ? [] : '');
const options = ref<
	{
		label: string;
		value: string;
	}[]
>([]);
// 绑定关系
const $emit = defineEmits(['update:modelValue', 'change']);
const dxLayerFormShowId = inject('dxLayerFormShowId', '');
function getList(keyword?: string, op = 'like') {
	let query: any = {
		more: props.more,
	};
	if (keyword) {
		loading.value = true;
		query[props.searchField || props.labelField] = {
			op,
			value: keyword,
		};
	}
	if (props.valueField && props.modelValue) {
		if (props.type === 'edit') {
			if (Array.isArray(props.modelValue)) {
				query[props.valueField] = {
					op: 'in',
					value: props.modelValue,
				};
			} else {
				query[props.valueField] = props.modelValue;
			}
		}
		query['selectPage'] = 1;
	} else {
		query['selectPage'] = '';
	}
	if (typeof props.params === 'object') {
		query = { ...query, ...props.params };
	}
	axios
		.send(props.url, props.funcName, query)
		.then((res) => {
			if (res.code === 1000) {
				let data = res.data?.list !== void 0 ? res.data.list : res.data;
				options.value = data.map((item: { [x: string]: any }) => {
					return {
						label: item[props.labelField],
						value: item[props.valueField],
					};
				});
			} else {
				ElMessage.error(res.message);
			}
		})
		.finally(() => {
			loading.value = false;
		});
}
watch(
	() => props.modelValue,
	(newProps) => {
		value.value = newProps;
	},
	{
		immediate: true,
	}
);
function change(val: any) {
	$emit('update:modelValue', val);
	$emit('change', {value:[...val], list:[...options.value]});
	emitTrigger();
}
function refreshList() {
	setTimeout(() => getList(''), 200);
}
onMounted(() => {
	refreshList();
	if (dxLayerFormShowId) uni.$on(dxLayerFormShowId, refreshList);
});
onUnmounted(() => {
	if (dxLayerFormShowId) uni.$off(dxLayerFormShowId, refreshList);
});
</script>
